<template>
	<!-- 线上培训 -->
	<view class="xspx">
		<view class="content">
			<view class="main">
				<view class="row">
					<view class="left">培训公司</view>
					<view class="right">
						<input type="text" v-model="form.company" placeholder="请输入培训公司名称" :disabled="isView" />
					</view>
				</view>
				<view class="row">
					<view class="left">联系人</view>
					<view class="right">
						<input type="text" v-model="form.contact" placeholder="请输入联系人" :disabled="isView" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">培训内容</view>
					<view class="right">
						<textarea class="textarea" v-model="form.content" placeholder="请输入培训内容" :disabled="isView" />
					</view>
				</view>
				<view class="row">
					<view class="left">培训时间</view>
					<view class="right">
						<picker mode="date" :value="form.time" @change="onTimeChange" :disabled="isView">
							<view class="picker">
								<input type="text" disabled v-model="form.time" placeholder="请选择培训时间" />
								<uni-icons type="right" size="17" color="#adadad"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
				<view class="row">
					<view class="left">会议链接</view>
					<view class="right">
						<input type="text" v-model="form.link" placeholder="请输入会议链接" :disabled="isView" @click="copyLink" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">宣传图<text>（避免审核不通过，建议上传高清图片，大小比例4:3。）</text></view>
					<view class="right">
						<view class="upload-wrapper">
							<view class="upload-btn" @click="chooseImage" v-if="!isView && !form.image">
								<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
								<text>上传图片</text>
							</view>
							<view class="image-list" v-if="form.image">
								<image :src="form.image" mode="aspectFill" @click="previewImage"></image>
								<view class="delete-btn" @click="deleteImage" v-if="!isView">
									<text class="delete-icon">×</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="tip-text">
					<text>1、请确保填写的信息真实有效；</text>
					<text>2、请勿发布违反国家法律法规的内容。</text>
				</view>
			</view>
			<button class="submit-btn" @click="submit" :class="{ active: isBtnActive }" @touchstart="isBtnActive = true"
				@touchend="isBtnActive = false">
				{{isView ? '返回' : (isEdit ? '确认修改' : '提交')}}
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					company: '', // 培训公司名称
					contact: '', // 联系人姓名
					content: '', // 培训内容描述
					time: '', // 培训时间，格式：YYYY-MM-DD
					link: '', // 会议链接地址
					image: '' // 宣传图片URL
				},
				isBtnActive: false,
				isView: false,
				isEdit: false,
				id: ''
			}
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id;
				this.isView = options.type === 'view';
				this.isEdit = options.type === 'edit';
				this.getDetail();
			}
		},
		methods: {
			async getDetail() {
				try {
					if (this.id) {
						const res = await this.$api.getTrainInfo(this.id);
						if (res.succ) {
							this.form = res.data;
						}
					}
				} catch (error) {
					console.error('获取详情失败:', error);
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					});
				}
			},
			onTimeChange(e) {
				this.form.time = e.detail.value;
			},
			// 选择图片
			async chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed', 'original'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
							return;
						}

						// 先进行图片裁剪
						uni.cropImage({
							src: res.tempFilePaths[0],
							cropScale: '4:3', // 设置裁剪比例为4:3
							quality: 100, // 设置裁剪后的图片质量为100
							success: async (cropRes) => {
								uni.showLoading({
									title: '上传中...'
								});

								try {
									const uploadRes = await uni.uploadFile({
										url: 'https://luntan.xiaouyf.cn/apis/custom/service/upload',
										filePath: cropRes.tempFilePath, // 使用裁剪后的图片路径
										name: 'multipartFile',
										formData: {
											'type': 'image'
										},
										success: (uploadRes) => {
											console.log('上传响应:', uploadRes);
											const result = JSON.parse(uploadRes.data);
											if (result.code === 200) {
												this.form.image = 'https://luntan.xiaouyf.cn/' + result.data;
												uni.hideLoading();
											} else {
												throw new Error(result.msg || '上传失败');
											}
										},
										fail: (error) => {
											console.error('上传失败:', error);
											throw new Error('上传失败: ' + JSON.stringify(error));
										}
									});
								} catch (error) {
									uni.hideLoading();
									uni.showToast({
										title: error.message || '上传失败',
										icon: 'none'
									});
								}
							},
							fail: (error) => {
								uni.showToast({
									title: '裁剪失败',
									icon: 'none'
								});
							}
						});
					},
					fail: () => {
						// 用户取消选择时不显示提示
					}
				});
			},
			// 预览图片
			previewImage() {
				uni.previewImage({
					urls: [this.form.image],
					current: this.form.image
				});
			},
			// 删除图片
			deleteImage() {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.form.image = '';
						}
					}
				});
			},
			// 提交
			async submit() {
				if (this.isView) {
					uni.navigateBack();
					return;
				}

				// 表单验证
				if (!this.form.company) {
					uni.showToast({
						title: '请输入培训公司',
						icon: 'none'
					});
					return;
				}
				if (!this.form.contact) {
					uni.showToast({
						title: '请输入联系人',
						icon: 'none'
					});
					return;
				}
				if (!this.form.content) {
					uni.showToast({
						title: '请输入培训内容',
						icon: 'none'
					});
					return;
				}
				if (!this.form.time) {
					uni.showToast({
						title: '请选择培训时间',
						icon: 'none'
					});
					return;
				}
				if (!this.form.link) {
					uni.showToast({
						title: '请输入会议链接',
						icon: 'none'
					});
					return;
				}

				try {
					if (this.isEdit) {
						// 调用编辑接口
						const res = await this.$api.getTrainUpdate({
							...this.form,
							guid: this.id,
							createUserId: this.$store.state.user.userInfo.guid
						});
						if (res.succ) {
							uni.showToast({
								title: '修改成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}
					} else {
						// 调用新增接口
						const res = await this.$api.infoTrainApply({
							...this.form,
							createUserId: this.$store.state.user.userInfo.guid
						});
						if (res.succ) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/my-xspx/my-xspx'
								});
							}, 1500);
						}
					}
				} catch (error) {
					uni.showToast({
						title: this.isEdit ? '修改失败' : '提交失败',
						icon: 'none'
					});
				}
			},
			// 复制链接
			copyLink() {
				if (this.isView && this.form.link) {
					uni.setClipboardData({
						data: this.form.link,
						success: () => {
							uni.showToast({
								title: '复制成功',
								icon: 'success'
							});
						}
					});
				}
			}
		}
	}
</script>

<style lang="less">
	.xspx {
		height: 100%;
		background: linear-gradient(180deg, #FAEBDB 0%, rgba(255, 247, 238, 0) 500rpx);

		.content {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			padding: 0 30rpx;

			.main {
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow: auto;
			}
		}

		.row {
			position: relative;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #333;

			&:after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 1px;
				background-color: #e8e8e8;
				transform: scaleY(0.5);
			}

			.left {
				font-size: 32rpx;
				padding: 40rpx 0;
			}

			.right {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: flex-end;

				input {
					width: 100%;
					border: 0;
					text-align: right;
					font-size: 32rpx;
					color: #333;
				}

				.picker {
					width: 100%;
					display: flex;
					align-items: center;

					input {
						flex: 1;
						margin-right: 10rpx;
						color: #333;
					}
				}
			}

			&.row-column {
				flex-direction: column;
				align-items: flex-start;

				&::after {
					display: none;
				}
				.left{
					text{
						color: #999;
						font-size: 26rpx;
					}
				}

				.right {
					width: 100%;
					flex: none;

					.textarea {
						width: 100%;
						height: 200rpx;
						padding: 20rpx 30rpx;
						box-sizing: border-box;
						border: 1px solid #e8e8e8;
						border-radius: 10rpx;
						color: #333;
					}

					.upload-wrapper {
						width: 100%;

						.upload-btn {
							width: 200rpx;
							height: 200rpx;
							background: #F5F5F5;
							border-radius: 10rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;

							text {
								font-size: 24rpx;
								color: #999;
								margin-top: 10rpx;
							}
						}

						.image-list {
							position: relative;
							width: 200rpx;
							height: 200rpx;

							image {
								width: 100%;
								height: 100%;
								border-radius: 10rpx;
							}

							.delete-btn {
								position: absolute;
								top: -20rpx;
								right: -20rpx;
								width: 44rpx;
								height: 44rpx;
								background: #fff;
								border-radius: 50%;
								display: flex;
								align-items: center;
								justify-content: center;
								border: 2rpx solid #ff4d4f;
								box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

								.delete-icon {
									color: #ff4d4f;
									font-size: 36rpx;
									font-weight: bold;
									line-height: 1;
									margin-top: -4rpx;
								}
							}
						}
					}
				}
			}
		}

		.tip-text {
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			margin: 30rpx 0;
			padding: 30rpx;
			background: #FFF7EE;
			border-radius: 10rpx;

			text {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				color: #AC6C17;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		.submit-btn {
			margin: 40rpx 0;
			height: 88rpx;
			line-height: 88rpx;
			background: linear-gradient(138deg, #F3B359 0%, #EC6A34 100%);
			border-radius: 44rpx;
			color: #fff;
			font-size: 32rpx;

			&.active {
				opacity: 0.8;
			}
		}
	}
</style>